﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CustomTempData.Controllers
{
    public class CacheTempDataProvider: ITempDataProvider
    {
        private const string keyName = "__TempData";
        public IDictionary<string, object> LoadTempData(
            ControllerContext controllerContext)
        {
            string cacheKey = GetCacheKey(controllerContext.HttpContext);
            Dictionary<string, object> tempData =
                controllerContext.HttpContext.Cache[cacheKey]
                as Dictionary<string, object>;
            if(tempData!=null)
            {
                controllerContext.HttpContext.Cache.Remove(keyName);
                return tempData;
            }
            return new Dictionary<string, object>();
        }

        public void SaveTempData(ControllerContext controllerContext,
            IDictionary<string, object> values)
        {
            string cacheKey = GetCacheKey(controllerContext.HttpContext);
            controllerContext.HttpContext.Cache.Insert(cacheKey, values);
        }

        private string GetCacheKey(HttpContextBase httpContext)
        {
            string uniqueIdentifier = httpContext.Request.UserHostAddress;
            return String.Format("{0}[{1}]",keyName, uniqueIdentifier);
        }
    }
}
